use windows_sys::Win32::{
    Foundation::{CloseHandle, GetLastError, ERROR_ALREADY_EXISTS, HANDLE},
    System::Threading::CreateMutexA, // feature: Win32_Security
};

//pub type HANDLE = *mut core::ffi::c_void;

pub fn get_app_handle(app_name: &str) -> Result<HANDLE, String> {
    let key = format!("Local\\{}", app_name);
    let mutex_name = std::ffi::CString::new(key).map_err(|e| e.to_string())?;

    unsafe {
        let handle: HANDLE = CreateMutexA(
            std::ptr::null_mut(), // 默认安全属性
            0,                    // 初始是否拥有互斥量（FALSE）
            mutex_name.as_ptr() as *const u8,
        );

        if handle == std::ptr::null_mut() {
            return Err("CreateMutexA failed.".to_string());
        }

        let last_error = GetLastError();
        if last_error == ERROR_ALREADY_EXISTS {
            CloseHandle(handle);
            return Err("Another instance is already running.".to_string());
        }

        Ok(handle)
    }
}

pub fn close_app_handle(handle: HANDLE) {
    unsafe {
        CloseHandle(handle);
    }
}
